<?php

namespace app\server\model;

class ControlFilter
{

    private $_whitelist = [];
    private $_blacklist = [];

    /**
     * TCP白名单
     *
     * @var array
     */
    private $_tcpWhitelist = [
        '127.0.0.1',
        '192.168.1.79',
        '192.168.1.12',
        '192.168.1.85',
        '192.168.1.87',
        '192.168.1.88',
    ];

    /**
     * TCP黑名单
     *
     * @var array
     */
    private $_tcpBlacklist = [];

    /**
     * HTTP白名单 请求接口端
     *
     * @var array
     */
    private $_httpWhitelist = [
        '127.0.0.1',
        '192.168.1.79',
        '192.168.1.12',
        '192.168.1.85',
        '192.168.1.87',
        '192.168.1.88'
    ];

    /**
     * HTTP黑名单
     *
     * @var array
     */
    private $_httpBlacklist = [];

    public function __construct($type = 'tcp')
    {
        if ($type == 'tcp') {
            $this->_whitelist = $this->_tcpWhitelist;
            $this->_blacklist = $this->_tcpBlacklist;
        }

        if ($type == 'http') {
            $this->_whitelist = $this->_httpWhitelist;
            $this->_blacklist = $this->_httpBlacklist;
        }
    }

    /**
     * 判断客服端是否可以连接
     *
     * @param $ip
     * @return boolean
     */
    public function checkClient($ip)
    {
        if (strpos($ip, ':') !== false) {
            $arr = explode(':', $ip);
            $ip = $arr[0];
        }
        return $this->_checkWhite($ip) && !$this->_checkBlack($ip);
    }

    /**
     * 检查白名单
     *
     * @param $ip
     * @return boolean
     */
    private function _checkWhite($ip)
    {
        return in_array($ip, $this->_whitelist);
    }

    /**
     * 检查黑名单
     *
     * @param $ip
     * @return boolean
     */
    private function _checkBlack($ip)
    {
        return in_array($ip, $this->_blacklist);
    }

}